import { makeAutoObservable } from 'mobx'
import { getClassList, getTrainList } from '../api/index'
import type { TrainParams, TrainInfo, ClassParams, ClassInfo } from '../api/interface'

type ClassRequestParams = Partial<ClassParams> & { search?: boolean }
type TrainRequestParams = Partial<TrainParams> & { search?: boolean }

class Store {
    activeTab: string = 'trainPlan'
    trainListParams: TrainParams = {
        page: 1,
        per_page: 10,
    }
    trainListTotal: number = 0
    trainList: TrainInfo[] = []
    trainHasMore = false

    classListParams: ClassParams = {
        page: 1,
        per_page: 10,
    }
    classListTotal: number = 0
    classList: ClassInfo[] = []
    classHasMore = false

    constructor() {
        makeAutoObservable(this)
    }

    setActiveTab = (newTab: string) => {
        this.activeTab = newTab
    }

    async queryClassList(search: boolean) {
        let params = { ...this.classListParams }
        const res = await getClassList(params)
        if (res.data) {
            const { total = 0, list = [] } = res.data
            this.classList = search ? list : [...list, ...this.classList]
            this.classListTotal = total
            this.classHasMore = total && this.classList.length < total
        }
    }

    setClassParams = ({ search = false, ...params }: ClassRequestParams) => {
        this.classListParams = {
            ...this.classListParams,
            ...params,
        }
        this.queryClassList(search)
    }

    async queryTrainList(search: boolean) {
        let params = { ...this.trainListParams }
        const res = await getTrainList(params)
        if (res.data) {
            const { total = 0, list = [] } = res.data
            this.trainList = search ? list : [...list, ...this.trainList]
            this.trainListTotal = total
            this.trainHasMore = total && this.trainList.length < total
        }
    }

    setTrainParams = ({ search = false, ...params }: TrainRequestParams) => {
        this.trainListParams = {
            ...this.trainListParams,
            ...params,
        }
        this.queryTrainList(search)
    }

    setParams = (params: TrainRequestParams | ClassRequestParams) => {
        if (this.activeTab === 'classManage') {
            this.setClassParams(params as ClassRequestParams)
        } else if (this.activeTab === 'trainPlan') {
            this.setTrainParams(params as TrainRequestParams)
        } else {
        }
    }
    resetPrams = () => {
        this.trainListParams = {
            page: 1,
            per_page: 10,
        }
        if (this.activeTab === 'classManage') {
            this.queryClassList(true)
        } else if (this.activeTab === 'trainPlan') {
            this.queryTrainList(true)
        } else {
        }
    }
}

export default new Store()
